const express = require("express");
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const router = express.Router();
// 确保file目录存在
const fileDirectory = path.join(__dirname, "..", "file");
fs.existsSync(fileDirectory) || fs.mkdirSync(fileDirectory);

// 配置Multer
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, fileDirectory); // 文件存储路径
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(
      null,
      file.originalname + "-" + uniqueSuffix + path.extname(file.originalname)
    );
  },
});

const upload = multer({ storage: storage });

// 文件上传路由
router.post("/", upload.single("file"), (req, res) => {
  if (!req.file) {
    return res.status(400).send("No file uploaded.");
  }
  res.send({
    message: "File uploaded successfully!",
    filename: req.file.filename,
  });
});

module.exports = router;
